package com.wlps.service.function;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.wlps.bo.OrderBO;
import com.wlps.bo.QueryComposeBo;
import com.wlps.config.RedisService;
import com.wlps.controller.OrderCenter;
import com.wlps.entity.*;
import com.wlps.service.*;
import com.wlps.vo.DispatchingManagementVo;
import com.wlps.vo.OrderCommodityVo;
import com.wlps.vo.ReceiptVo;
import com.wlps.vo.SenderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class DispatchingMangementCenter{

    @Resource
    private IOrderService orderService;

    public OrderCenter getOrderCenter() {
        return orderCenter;
    }

    public ICommodityOrderService getCommodityOrderService() {
        return commodityOrderService;
    }

    @Resource
    private ICommodityOrderService commodityOrderService;
    @Autowired
    private OrderCenter orderCenter;

    @Resource
    private ISysUserService sysUserService;

    public IMissionListService getMissionListService() {
        return missionListService;
    }

    @Resource
    private IMissionListService missionListService;

    @Resource
    private RedisService redisService;
    @Resource
    private ICommodityMissionListService commodityMissionListService;
    public List<DispatchingManagementVo> queryAllDispatchManagement(){
       return orderService.queryDispachment();
    }

    public DispatchingManagementVo queryOneDispatchManagement(long id){
        List<DispatchingManagementVo> dispatchingManagementVos = orderService.queryDispachment();
        return dispatchingManagementVos.stream().filter(data -> data.getId() == id).collect(Collectors.toList()).get(0);
    }
    public OrderCommodityVo queryDetailOrderById(long id){
             return orderService.queryDetailById(id);
    }

    public List<DispatchingManagementVo> queryDispatchManagementByRequire(QueryComposeBo queryComposeBo){
        String queryType = queryComposeBo.getQueryType();
        List<DispatchingManagementVo> dispatchingManagementVos = orderService.queryDispachment();
        Stream<DispatchingManagementVo> dispatchingManagementVoStream = null;
        switch (queryType){
            case "订单类型":
                 dispatchingManagementVoStream = dispatchingManagementVos.stream().filter(data -> data.getOrderType() == Long.parseLong(queryComposeBo.getQueryContain()));
                break;
            case "订单状态":
                dispatchingManagementVoStream=dispatchingManagementVos.stream().filter(data->data.getOrderStatus()==Long.parseLong(queryComposeBo.getQueryContain()));
                break;
            case "客户姓名":
                dispatchingManagementVoStream=dispatchingManagementVos.stream().filter(data->data.getName().equals(queryComposeBo.getQueryContain()));
                break;
            case "联系电话":
                dispatchingManagementVoStream=dispatchingManagementVos.stream().filter(data->data.getPhone().equals(queryComposeBo.getQueryContain()));
        }
        assert dispatchingManagementVoStream != null :"queryType输入格式不符合";
        if(queryComposeBo.getCreateTime()!=null) {
            dispatchingManagementVoStream=dispatchingManagementVoStream.filter(data->data.getFinishDate().after(queryComposeBo.getFinishTime()));
        }
        if(queryComposeBo.getFinishTime()!=null){
            dispatchingManagementVoStream=dispatchingManagementVoStream.filter(data->data.getFinishDate().before(queryComposeBo.getFinishTime()));
        }
        return dispatchingManagementVoStream.collect(Collectors.toList());
    }
    public Order queryOrderById(long id){
        return orderCenter.queryOrder(id);
    }

    public List<SenderVo> querySender(){
        List<SysUser> users = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptName, "物流部"));
        return users.stream().map(data -> new SenderVo(data.getId(), data.getMobile())).collect(Collectors.toList());
    }

    public Order updateStatus(long orderId,Integer status){
        Order order = orderCenter.queryOrder(orderId);
        if(order==null)
            throw new RuntimeException("不存在该订单");
        order.setOrderStatus(status);
        orderCenter.updateOrder(order);
        return order;
    }
    /**
     *   更新任务单真正的配送
     *
     * @param userId  员工id
     * @param orderId 订单id
     * @param serviceMoney  服务费
     * @param remark 任务单
     * @return c任务单
     */
    @Transactional
    public MissionList updateMissionList(long userId,long orderId,Double serviceMoney,String remark){
        Order order = orderCenter.queryOrder(orderId);
        if(order==null)
            throw new RuntimeException("不存在该订单无法生成任务单");
        SysUser user = sysUserService.getById(userId);
        order.setDeliveryInformation(user.getUsername()+"-"+user.getMobile());
        order.setOrderStatus(2);//2表示调度中
        MissionList missionList = new MissionList(userId, orderId, order.getClientId(),order.getOrderType(),serviceMoney,remark);
        missionList.setTaskType(order.getOrderType());
        missionList.setTaskStatus(-1);
        missionListService.update(missionList,new LambdaUpdateWrapper<MissionList>().eq(MissionList::getOrderId,orderId));
        return missionList;
    }

    public MissionList generatorMissionList(long orderId){
        Order order = orderCenter.queryOrder(orderId);
        if(order==null)
            throw new RuntimeException("不存在该订单无法生成任务单");
        order.setDeliveryInformation("未传入配送员");
        order.setOrderStatus(2);//2表示调度中
        MissionList missionList = new MissionList(-1L, orderId, order.getClientId(),order.getOrderType(),-1.0,"无");
        missionListService.save(missionList);
        List<Commodity> commodityList = this.queryDetailOrderById(orderId).getCommodityList();
        List<OrderBO> byId =(List<OrderBO>) redisService.get(String.valueOf(orderId));
        if(byId==null){
            throw new RuntimeException("redis数据被删除");
        }
        Map<Long, Integer> collect = byId.stream().collect(Collectors.toMap(OrderBO::getCommodityId, OrderBO::getNumber));
        ArrayList<CommodityMissionList> commodityMissionLists = new ArrayList<>();
        commodityList.forEach(data->{
                    long number=0;
                    if(collect.containsKey(data.getId())){
                        number=collect.get(data.getId());
                        Long MissionId=missionList.getId();
                        long commodityId=data.getId();
                        CommodityMissionList commodityMissionList = new CommodityMissionList()
                                .setAmountOfGoods(number).setCommodityId(commodityId).setMissionListId(MissionId);
                        commodityMissionLists.add(commodityMissionList);
                    }
                }
        );
        commodityMissionListService.saveBatch(commodityMissionLists);
        return missionList;
    }

    public MissionList queryMissionListById(long id){
        MissionList byId = missionListService.getById(id);
        if(byId==null)
            throw new RuntimeException("不存在任务单");
        return byId;
    }
    public boolean updateRecepitMissionList(long id,Integer status,String satisfaction,String remark){
        MissionList missionList = queryMissionListById(id);
        missionList.setTaskStatus(status);
        missionList.setCustomerSatisfaction(satisfaction);
        missionList.setRemark(remark);
        return missionListService.updateById(missionList);
    }

    public ReceiptVo printReceiptVo(long id){
        return missionListService.recepitById(id);
    }

    public boolean deleteOrder(long id){
       return orderCenter.deleteOrder(id);
    }


}